let cart =require('../model/cart.js')
let {Op}=require('sequelize')
let goods=require('../model/goods.js')

async function addCarts(user_id,goods){

    let {goods_id,num,selected}=goods

    let res=await cart.findOne({
        where:{
            [Op.and]:{
                user_id:user_id*1,
                goods_id:goods_id*1,
            }
        }
    })

    if(res){
        let updateRes=await cart.update({num,selected},{
            where:{
                user_id:user_id*1,
                goods_id:goods_id*1,
            }
        })
        return updateRes[0]>0?true:false
    }else{
        let createRes=await cart.create({
            user_id:user_id*1,
            goods_id:goods_id*1,
            number:num*1,
            selected:selected==='true'?true:false
        })
        return createRes.dataValues
    }
}

async function find(pageSize,pageNum){
    let offset=(pageNum-1)*pageSize

    let {count,rows}=await cart.findAndCountAll({
        attributes:['id','number','selected'],
        offset,
        limit:pageSize*1,
        include:{
            model:goods,
            as:"goods_info",
            attributes:['id','name','img','price']
        }
    })
    console.log(rows)
    return {
        pageSize,
        pageNum,
        total:count,
        list:rows
    }
}

async function deleteCarts(id){
    let ids=id.split(',')
    let res=await cart.destroy({where:{
        id:{
            [Op.in]:ids
        }
    }})
    return res
}

module.exports={addCarts,find,deleteCarts}